package com.oriental.manage.controller.payCount;

import com.oriental.manage.controller.opcif.CountMap;
import com.oriental.manage.core.excelUtils.ExcelTemplateUtil;
import com.oriental.manage.core.fileUtils.ExcelContentExt;
import com.oriental.manage.core.fileUtils.FileDownAjax;
import com.oriental.manage.core.fileUtils.HeaderExt;
import com.oriental.manage.core.response.ResponseDTO;
import com.oriental.manage.core.system.Constants;
import com.oriental.manage.core.system.log.OperateLogger;
import com.oriental.manage.core.utils.Bean2MapUtil;
import com.oriental.manage.core.utils.DateUtils;
import com.oriental.manage.pojo.payCount.PayTransCountModel;
import com.oriental.manage.pojo.payCount.PayTransCountReqModel;
import com.oriental.manage.pojo.payCount.PayTransCountRespModel;
import com.oriental.manage.service.payCount.PayTransCountService;
import com.oriental.paycenter.commons.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.webbuilder.office.excel.config.ExcelWriterConfig;
import org.webbuilder.office.excel.config.Header;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by Chuch on 2017/5/1
 */
@Slf4j
@Controller
@RequestMapping("count/pay")
public class PayTransCountController {
    public static final long DEFAULT_DAY = 92;

    @Autowired
    private PayTransCountService payTransCountService;

    @Autowired
    private Constants constants;
    @Autowired
    private FileDownAjax fileDownAjax;

    @RequestMapping("init")
//    @RequiresPermissions("payTransCountReport_search")
    public String init() {
        return "payCount/payTransCountReport";
    }

    @OperateLogger(content = "支付报表查询", operationType = OperateLogger.OperationType.R)
    @RequestMapping("/search")
//    @RequiresPermissions("payTransCountReport_search")
    @ResponseBody
    public ResponseDTO<List<PayTransCountRespModel>> queryPage(@RequestBody PayTransCountModel pcrm) {
        ResponseDTO<List<PayTransCountRespModel>> responseDTO = new ResponseDTO<List<PayTransCountRespModel>>();
        try {
            if (pcrm.getStartTime() == null || pcrm.getEndTime() == null) {
                pcrm.setEndTime(DateUtil.getCurrent(DateUtil.datePattern));
                pcrm.setStartTime(DateUtil.format(new Date(System.currentTimeMillis() - DEFAULT_DAY * 24 * 3600 * 1000), DateUtil.datePattern));
            } else {
                long endTime = DateUtil.parse(pcrm.getEndTime(), DateUtil.datePattern).getTime();
                long startTime = DateUtil.parse(pcrm.getStartTime(), DateUtil.datePattern).getTime();
                if (endTime > startTime + DEFAULT_DAY * 24 * 3600 * 1000) {
                    log.error("交易统计查询失败，查询时间大于{}", DEFAULT_DAY);
                    responseDTO.setSuccess(false);
                    responseDTO.setMsg("查询时间不能大于" + DEFAULT_DAY + "天");
                    return responseDTO;
                }
            }
            List<PayTransCountRespModel> list = payTransCountService.queryTransCount(pcrm);

            responseDTO.setSuccess(true);
            responseDTO.setObject(list);
        } catch (Exception e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }


    @RequiresPermissions("refund-report_download")
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(@RequestBody PayTransCountReqModel pcrm) {
        ResponseEntity<byte[]> responseEntity;
        File tempFile = null;
        try {
            InputStream inputStream = new FileInputStream(constants.getExcelPath() + "/支付报表.xlsx");
            tempFile = fileDownAjax.touch("支付报表" + DateUtils.now() + ".xlsx");

            PayTransCountModel pc =new PayTransCountModel();
            pc.setBankCode(pcrm.getBankCode());
            pc.setStartTime(DateUtil.format(pcrm.getStartTime(),DateUtil.datePattern));
            pc.setEndTime(DateUtil.format(pcrm.getEndTime(),DateUtil.datePattern));
            List<PayTransCountRespModel> list = payTransCountService.queryTransCount(pc);
            //表头
            LinkedList<Header> tHeaders = new LinkedList<>();
            //内容
            List<Object> datas = new ArrayList<>();
            //添加表头
            tHeaders.add(new HeaderExt("序号", "index"));
            tHeaders.add(new HeaderExt("支付机构", "orgCode", ExcelContentExt.ORGANIZE));
            tHeaders.add(new HeaderExt("银行名称", "bankCode", ExcelContentExt.BANK_INFO));
            tHeaders.add(new HeaderExt("交易开始日期", "startTime"));
            tHeaders.add(new HeaderExt("交易结束日期", "endTime"));
            tHeaders.add(new HeaderExt("笔数", "paySuccessTotal"));
            tHeaders.add(new HeaderExt("金额", "paySuccessMoney", ExcelContentExt.CURRENCY));
            tHeaders.add(new HeaderExt("笔数", "payFailTotal"));
            tHeaders.add(new HeaderExt("金额", "payFailMoney", ExcelContentExt.CURRENCY));
            tHeaders.add(new HeaderExt("失败笔数占比", "payFailRate"));

            int i = 1;
            int suc=0;
            long sucAmt=0;
            int fail=0;
            long failAmt=0;
            String payFailRate="";
            for(PayTransCountRespModel payTransCountRespModel:list){
                if(payTransCountRespModel.getOrgCode()==null){
                    payTransCountRespModel.setOrgCode("未知");
                }
                if(payTransCountRespModel.getBankCode()==null){
                    payTransCountRespModel.setBankCode("未知");
                }else{
                    payTransCountRespModel.setBankCode(CountMap.getBankName(payTransCountRespModel.getBankCode()));
                }
                Map map=Bean2MapUtil.convertBean(payTransCountRespModel);
                suc+=payTransCountRespModel.getPaySuccessTotal();
                sucAmt+=payTransCountRespModel.getPaySuccessMoney();
                fail+=payTransCountRespModel.getPayFailTotal();
                failAmt+=payTransCountRespModel.getPayFailMoney();
                payFailRate=division(fail,suc+fail);
                map.put("index",i);
                i++;
                datas.add(map);
            }


            /**
             * 增加一行合计
             */
            if (list.size() > 0) {
                Map map = Bean2MapUtil.convertBean(PayTransCountRespModel.class);
                map.put("endTime","合计");
                map.put("paySuccessTotal",suc);
                map.put("paySuccessMoney",sucAmt);
                map.put("payFailTotal",fail);
                map.put("payFailMoney",failAmt);
                map.put("payFailRate",payFailRate);
                datas.add(map);
            }



            ExcelWriterConfig config = new ExcelWriterConfig();
            config.setHeaders(tHeaders);
            config.setDatas(datas);
            config.setStartWith(4);

            FileOutputStream outputStream = new FileOutputStream(tempFile);
            ExcelTemplateUtil.write(inputStream, outputStream, config);
            responseEntity = fileDownAjax.getResponseEntity(tempFile);
        } catch (Exception e) {
            log.error("下载失败", e);
            responseEntity = fileDownAjax.getResponseEntityFail();
        } finally {
            fileDownAjax.forceDelete(tempFile);
        }
        return responseEntity;
    }


    private static String division(int a, int b) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format((float) (a*100) / b)+"%";
    }

}
